package com.jiangnan.ui.fragment

import android.os.Bundle
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.jiangnan.R
import com.jiangnan.databinding.FragmentRecommendBinding
import com.jiangnan.repository.DeepSeekRepository
import com.jiangnan.viewmodel.DeepSeekViewModel
import com.jiangnan.viewmodel.DeepSeekViewModelFactory

class RecommendFragment : Fragment() {

    private var _binding: FragmentRecommendBinding? = null
    private val binding get() = _binding!!

    private lateinit var viewModel: DeepSeekViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 告诉系统该 Fragment 有菜单
        setHasOptionsMenu(true)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentRecommendBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 1. 初始化 Repository 和 ViewModel
        val repository = DeepSeekRepository()
        val factory = DeepSeekViewModelFactory(repository)
        viewModel = ViewModelProvider(this, factory).get(DeepSeekViewModel::class.java)

        // 2. DataBinding 绑定 ViewModel + LifecycleOwner
        binding.viewModel = viewModel
        binding.lifecycleOwner = viewLifecycleOwner

        // 3. 设置 Toolbar
        (activity as? AppCompatActivity)?.setSupportActionBar(binding.toolbar)
        (activity as? AppCompatActivity)?.supportActionBar?.setDisplayHomeAsUpEnabled(false)
        (activity as? AppCompatActivity)?.supportActionBar?.title = "图书AI管家"

        // 4. 点击“发送”按钮 -> 调用 ViewModel
        binding.btnSend.setOnClickListener {
            val userInput = binding.etUserInput.text.toString().trim()
            if (userInput.isNotEmpty()) {
                viewModel.sendChatStreamRequest(userInput)
                binding.etUserInput.setText("")
            }
        }
    }

    // 加载菜单
    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.menu_main, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    // 处理菜单点击事件
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_rabbish -> {
                // 清空聊天记录，回到初始界面
                viewModel.clearChat()
                return true
            }
//            android.R.id.home -> {
//                requireActivity().onBackPressedDispatcher.onBackPressed()
//                return true
//            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
